package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.AccessTokenResultDto;
import com.zzyl.dto.PhoneNumberResultDto;
import com.zzyl.dto.WeChatResultDto;
import com.zzyl.properties.WeChatProperties;
import com.zzyl.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public WeChatResultDto getCode2Session(String code) {
        String url="https://api.weixin.qq.com/sns/jscode2session";
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppId());
        map.put("secret", weChatProperties.getAppSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String res = HttpUtil.get(url, map);
        log.info("code2session result:{}", res);
        WeChatResultDto code2SessionDto = JSONUtil.toBean(res, WeChatResultDto.class);
        return code2SessionDto;
    }
    @Override
    public AccessTokenResultDto getAccessToken(){
        String url="https://api.weixin.qq.com/cgi-bin/token";
        HashMap<String, Object> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", weChatProperties.getAppId());
        map.put("secret", weChatProperties.getAppSecret());
        String res = HttpUtil.get(url, map);
        log.info("accessToken result:{}", res);
        AccessTokenResultDto accessTokenResponseDto = JSONUtil.toBean(res, AccessTokenResultDto.class);
        return accessTokenResponseDto;
    }

    @Override
    public PhoneNumberResultDto getPhoneNumber(String accessToken, String code){
        String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        String json = JSONUtil.toJsonStr(map);
        String res = HttpUtil.post(url, json);
        log.info("getPhoneNumber result:{}", res);
        PhoneNumberResultDto phoneNumberResultDto = JSONUtil.toBean(res, PhoneNumberResultDto.class);
        return phoneNumberResultDto;
    }

}
